package com.bsf.mvc.webdemo.base;

import com.bsf.mvc.controller.SpringController;
import com.bsf.serialization.json.JsonProvider;
import com.bsf.util.ExceptionUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 扩展SpringController的实现，采用lambada表达式的方式进行类似aop的拦截
 */
public class SpringMvcController extends SpringController {
    public SpringMvcController()
    {
        int a=1;
    }

    public interface IPageVisit
    {
        void invoke(ModelAndView modelAndView);
    }

    //页面统一默认拦截器 页面模式
    protected ModelAndView pageVisit(IPageVisit visit)
    {
        ModelAndView modelAndView = null;
        try {
            //页面模板扩展方法
            request.setAttribute("Html",new HtmlHelper());
            request.setAttribute("user",new User());

            //默认视图地址为/contoller name/method name,即结构对应一致
            modelAndView = new ModelAndView();
            visit.invoke(modelAndView);

            return modelAndView;
        }
        catch (Exception exp)
        {
            //默认错误拦截处理
            response.setStatus(500);
            modelAndView = new ModelAndView("forward:/systemerror/index/");
            request.setAttribute("error", ExceptionUtil.getDetailMessage(exp));
        }
        return  modelAndView;
    }


    public interface IJsonVisit
    {
        Object invoke(ModelAndView modelAndView);
    }
    //Json 统一序列化
    protected ModelAndView jsonVisit(IJsonVisit visit)
    {
        ModelAndView modelAndView = new ModelAndView("");
        response.addHeader("Access-Control-Allow-Origin", "*");//跨域支持
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {

            Object jsondata = visit.invoke(modelAndView);
            String json = new JsonProvider().serialize(jsondata);
            response.getWriter().write(json);
            modelAndView.setView(new View() {
                @Override
                public String getContentType() {
                    return null;
                }

                @Override
                public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

                }
            });
        }
        catch (Exception exp)
        {
            //默认错误拦截处理
            //response.setStatus(500);
           try{ response.getWriter().write( ExceptionUtil.getDetailMessage(exp));}catch (Exception e){}
        }
        return modelAndView;
    }

    protected void checkAdmin()
    {
        checkUser();
        if(!new User().isAdmin())
            throw new RuntimeException("无权限访问");
    }

    protected void checkUser()
    {
         if(new User().getCurrent() == null)
             throw new RuntimeException("用户未登陆");
    }
}
